package my.gps;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class GPSRecorderActivity extends Activity {
	private LocationManager lm;
	private LocationListener ll;
	private File sdCardroot;
	private File fileDir;
	private File logFile;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		ll = new Mylocationlistener();
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, ll);

		sdCardroot = Environment.getExternalStorageDirectory();
		fileDir = new File(sdCardroot + "/Android/data/my.gps/files/");
		logFile = new File(fileDir + "/GPSLog.txt");

		Button btn1 = (Button) findViewById(R.id.btn1);
		btn1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				if (location == null) {
					Toast.makeText(GPSRecorderActivity.this, "empty", Toast.LENGTH_SHORT).show();
				} else {
					String date = (String) DateFormat.format("yyyy-MM-dd hh:mm:ss ", new Date());
					String info = date + location.getLatitude() + " " + location.getLongitude() + " STOP";
					Toast.makeText(GPSRecorderActivity.this, info, Toast.LENGTH_SHORT).show();
					writeToLogfile(info);
				}
			}
		});
		Button btn2 = (Button) findViewById(R.id.btn2);
		btn2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (logFile != null && logFile.exists()) {
					String log = "";
					try {
						FileInputStream fileIS = new FileInputStream(logFile);
						BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
						String readString = new String();
						while ((readString = buf.readLine()) != null) {
							// Log.d("line: ", readString);
							log = log.concat(readString);
						}
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					Toast.makeText(GPSRecorderActivity.this, log, Toast.LENGTH_SHORT).show();
				}
			}
		});
		Button btn3 = (Button) findViewById(R.id.btn3);
		btn3.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (logFile != null && logFile.exists()) {
					String date = (String) DateFormat.format("_yyyy-MM-dd_hh-mm-ss", new Date());
					File backup = new File(fileDir + "/GPSLog" + date + ".txt");
					logFile.renameTo(backup);
					Toast.makeText(GPSRecorderActivity.this, "Back up " + backup.toString(), Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		lm.removeUpdates(ll);
	}

	private class Mylocationlistener implements LocationListener {
		@Override
		public void onLocationChanged(Location location) {
			if (location != null) {
				String date = (String) DateFormat.format("yyyy-MM-dd hh:mm:ss ", new Date());
				String info = date + location.getLatitude() + " " + location.getLongitude();
				writeToLogfile(info);
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

	private void writeToLogfile(String info) {
		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need
			// to know is we can neither read nor write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}

		if (mExternalStorageAvailable && mExternalStorageWriteable) {

			if (!fileDir.exists()) {
				fileDir.mkdirs();
			} else if (!logFile.exists()) {
				try {
					logFile.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				info = info + "\n";
				FileOutputStream fos = new FileOutputStream(logFile, true);
				fos.write(info.getBytes());
				fos.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}